define(['vue','jquery','ELEMENT','layer'],function (Vue,$,ELEMENT,layer){
    const {ElLoading,ElMessage,ElMessageBox } = ELEMENT;
    const mutable = {
        template:`
<div class="padding10 flex-row" v-if="hasSearch">
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item v-for="(ite,index) in seachObj" :label="ite.title">
            <template v-if="ite.type=='min-max'">
                
            </template>
            <template v-if="ite.type=='timerange'">
                <el-time-picker
                  v-model="ite.value"
                  is-range
                  value-format="HH:mm:ss"
                  range-separator="到"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                ></el-time-picker>
            </template>
            <template v-if="ite.type=='daterange'">
                <el-date-picker
                  v-model="ite.value"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  range-separator="到"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                ></el-date-picker>
            </template>
            <template v-if="ite.type=='datetimerange'">
                <el-date-picker
                  v-model="ite.value"
                  type="datetimerange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  range-separator="到"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                ></el-date-picker>
            </template>
<!--            文本查询-->
            <el-input v-if="ite.type=='text'" v-model="ite.value" :placeholder="'请填写'+ite.title" style="width: 200px"></el-input>
<!--            下拉查询-->
                <el-select v-if="ite.searchList&&ite.searchList!=[]" 
                clearable
                style="width: 200px"
                v-model="ite.value"
                :placeholder="'请选择'+ite.title"
                >
                    <template v-if="Array.isArray(ite.searchList)">
                        <el-option
                        v-for="(itemsA,keysA) in ite.searchList"
                        :key="itemsA.value"
                        :value="itemsA.value"
                        :label="itemsA.label"
                        ></el-option>
                    </template>
                    <template v-else>
                        <el-option
                        v-for="(itemsA,keysA) in ite.searchList"
                        :key="keysA"
                        :value="keysA"
                        :label="itemsA"
                        ></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-form-item>

        </el-form>
    </div>
        <div class="flex-row bottom10">
        <el-button @click="refresh" v-if="options&&options.toolbar&&options.toolbar.refresh">
            <el-icon :size="15"><Refresh /></el-icon>
        </el-button>

        <el-button v-if="options&&options.toolbar&&options.toolbar.add" type="primary" @click="handleAdd()">添加</el-button>
        <el-button type="danger" v-if="options&&options.toolbar&&options.toolbar.del" @click="event=>handleDels()" :disabled="selectables.length==0?true:false">删除</el-button>
        <template v-if="options&&options.toolbar&&options.toolbar.buttons.length>0">
            <el-button v-for="onebu in options.toolbar.buttons" :type="onebu.type?onebu.type:'primary'" @click="handClick(onebu)">{{onebu.title||onebu.text}}</el-button>
        </template>
    </div>
            <div class="flex-column flex-content-center flex-item-center">
        <el-table :data="tableObj.rows"
                  style="width: 100%"
                  :border="true"
                  :max-height="600"
                  size="default"
                  @selection-change="event=>handleSelectionChange(event)"
                  :show-overflow-tooltip="true"
                  :row-key="options.pk?options.pk:'id'"
        >
        <template v-for="item in options.columns">
            <template v-if="item.visible!==false">
                <el-table-column v-if="item.type&&item.type=='selection'" :fixed="item.fixed?item.fixed:'left'" type="selection"  :width="item.width?item.width:'55'" ></el-table-column>

                <el-table-column v-if="(item.type&&(item.type=='text'||item.type=='input')||!item.type)" :fixed="item.fixed?item.fixed:false" :prop="item.field" :label="item.title" :width="item.width?item.width:(item.field=='id'?'80':'')" :align="item.align?item.align:'center'" show-overflow-tooltip></el-table-column>
                <el-table-column v-if="item.type&&item.type=='img'" :prop="item.field" :label="item.title" :width="item.width?item.width:(item.field=='id'?'80':'')" :align="item.align?item.align:'center'">
                    <template #default="scope">
                        <el-image :src="scope.row[item.field]" style="width: 100px" fit="fill" :preview-src-list="[scope.row[item.field]]" :preview-teleported="true"></el-image>
                    </template>
                </el-table-column>
                <el-table-column v-if="item.type&&item.type=='imgs'" :prop="item.field" :label="item.title" :width="item.width?item.width:(item.field=='id'?'80':'')" :align="item.align?item.align:'center'">
                    <template #default="scope">
                        <span v-for="it in scope.row[item.field]">
                            <el-image :src="it" style="width: 100px" fit="fill" :preview-src-list="[it]" :preview-teleported="true"></el-image>
                        </span>
                    </template>
                </el-table-column>
                
                    <el-table-column v-if="item.type&&item.type=='normal'" :label="item.title" :width="item.width?item.width:(item.field=='id'?'80':'')" :align="item.align?item.align:'center'">
                        <template #default="{row}">
                            <span v-if="item.searchList">
                            <el-tag :type="tagsList[row[item.field]]?tagsList[row[item.field]]:'primary'">
                                    {{item.searchList[row[item.field]]}}
                                </el-tag>
                            </span>
                            <span v-else>
                                <el-tag type="primary" class="tag-item">
                                    {{row[item.field]}}
                                </el-tag>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="item.type&&item.type=='switch'" :label="item.title" :width="item.width?item.width:(item.field=='id'?'80':'')" :align="item.align?item.align:'center'">
                        <template #default="{row}">
                            <span v-if="item.searchList">
                            <span v-if="typeof row[item.field] == 'string'">
                                    <el-switch v-model="row[item.field]" active-value="1" inactive-value="0" :active-text="item.searchList[1]" :inactive-text="item.searchList[0]" @change="event=>beforeChange(event,row,item.field)"></el-switch>
                                </span>
                                <span v-else>
                                    <el-switch v-model="row[item.field]" :active-value="1" :inactive-value="0" :active-text="item.searchList[1]" :inactive-text="item.searchList[0]" @change="event=>beforeChange(event,row,item.field)"></el-switch>
                                </span>
                            </span>
                            <span v-else>
                               <span v-if="typeof row[item.field] == 'string'">
                                    <el-switch v-model="row[item.field]" active-value="1" inactive-value="0" @change="event=>beforeChange(event,row,item.field)"></el-switch>
                                </span>
                                <span v-else>
                                    <el-switch v-model="row[item.field]" :active-value="1" :inactive-value="0" @change="event=>beforeChange(event,row,item.field)"></el-switch>
                                </span>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="item.type&&(item.type=='datetime'||item.type=='datetimerange')" :label="item.title" :width="item.width?item.width:'200'" :align="item.align?item.align:'center'">
                        <template #default="{row}">
                            {{getDate(row[item.field])}}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="item.type&&(item.type=='date'||item.type=='daterange')" :label="item.title" :width="item.width?item.width:'200'" :align="item.align?item.align:'center'">
                        <template #default="{row}">
                            {{row[item.field]}}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="item.type&&(item.type=='time'||item.type=='timerange')" :label="item.title" :width="item.width?item.width:'200'" :align="item.align?item.align:'center'">
                        <template #default="{row}">
                            {{row[item.field]}}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="item.type&&item.type=='icon'" :label="item.title" :width="item.width?item.width:'200'" :align="item.align?item.align:'center'">
                        <template #default="{row}">
                            <el-icon :size="20"><Component :is="row[item.field]"></Component></el-icon>
                        </template>
                    </el-table-column>
                     <el-table-column v-if="item.type&&item.type=='operate'" :label="item.title" :width="item.width?item.width:''" :align="item.align?item.align:'center'" :fixed="item.fixed?item.fixed:false">
                        <template #default="{row}">
                            <el-button v-if="item.button&&item.button.includes('edit')"  size="small"  type="primary" @click="handEdit(row,item.area)">编辑</el-button>
                            <el-button v-if="item.button&&item.button.includes('del')"  size="small"  type="danger" @click="handDel(row)">删除</el-button>
                            <template v-if="item.buttons&&item.buttons.length>0">
                                <template v-for="onbutton in item.buttons">
                                    <el-button v-if="(typeof onbutton.visible == 'function')&&onbutton.visible(row)"  size="small"  :type="onbutton.type?onbutton.type:'primary'" @click="handClick(onbutton,row)">{{onbutton.title||onbutton.text}}</el-button>
                                    <el-button v-if="(typeof onbutton.visible == 'boolean')&&onbutton.visible"  size="small"  :type="onbutton.type?onbutton.type:'primary'" @click="handClick(onbutton,row)">{{onbutton.title||onbutton.text}}</el-button>
                                </template>
                                
                            </template>
                        </template>
                    </el-table-column>
                    
            </template>
 
        </template>
        </el-table>
    </div>
        <div class="flex-row top20 flex-content-end" v-if="!options.isTree">
        <el-pagination
                background
                layout="total,sizes,prev, pager, next,jumper"
                :total="tableObj.total"
                :page-size="tableObj.limit"
                :page-sizes="[10, 20, 50, 100,500,1000]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        ></el-pagination>
    </div>
        `,
        data(){
            return {
                selectables:[],
                hasSearch:true,
                seachObj:[],
                tableObj:{
                    page:1,
                    limit:10,
                    total:0,
                    rows:[]
                },
                // 标签
                tagsList:[
                    'primary',
                    'success',
                    'warning',
                    'danger',
                    'info'
                ],
                arrObj:[
                    'daterange',
                    'datetimerange',
                    'timerange',
                    'min-max'
                ]
            }
        },
        props:{
            options:{
                type:Object,
                default:function(){
                    return {}
                }
            }
        },
        created(){
            // console.log(this.options)
            let hasSearch = false
            let seachObj = []
            if(this.options.columns){
                this.options.columns.forEach(item=>{
                    if(item.operate!==false&&item.type!=='selection'&&item.type!=='operate'){
                        hasSearch = true
                        let type = item.type?item.type:'text'
                        let values = item.value?item.value:''
                        let operate = item.operate?item.operate:'='
                        if(item.type==='date'){
                            type = 'daterange'
                            values = [ '', '']
                            if(operate=='='){
                                operate = 'between'
                            }

                        }
                        if(item.type==='datetime'){
                            type = 'datetimerange'
                            values = [ '', '']
                            if(operate=='='){
                                operate = 'between'
                            }
                        }
                        if(item.type==='time'){
                            type = 'timerange'
                            values = [ '', '']
                            if(operate=='='){
                                operate = 'between'
                            }
                        }
                        if(item.operate==='between'||item.operate==='not between'){
                            values = [ '', '']
                            type = 'min-max'
                            if(operate=='='){
                                operate = 'between'
                            }
                        }
                        seachObj.push({
                            name:item.field,
                            value:values,
                            operate:operate,
                            title:item.title?item.title:item.field,
                            type:type,
                            searchList:item.searchList?item.searchList:false,
                        })
                    }
                })
            }
            this.hasSearch = hasSearch
            this.seachObj = seachObj
            this.getList()
            console.log(this.seachObj)
        },
        methods:{
            beforeChange(boolean,row,field){
                console.log(row,field)
                let ids = row[this.options.pk?this.options.pk:'id']
                let url = this.options?.urls?.multi?this.options.urls.multi:`/app/${Config.plugin}/${Config.app}/${Config.controller}/multi?ids=${ids}`
                let that = this
                let loading = true
                if("loading" in this.options){
                    loading = this.options.loading
                }
                let loadingInstance = null
                if(loading){
                    // console.log("loading")
                    loadingInstance = ElLoading.service({
                        fullscreen: true
                    });
                }
                let data = {
                    field:field,

                }
                $.ajax(url, {
                    method:'post',
                    data:data,
                    success:function (res){
                        if(res.code==1){
                            ElMessage({
                                type:'success',
                                message:res.msg?res.msg:'操作成功',
                                duration:1000,
                                onClose:function (){

                                }
                            })
                        }else{
                            ElMessage( {
                                type:'error',
                                message:res.msg?res.msg:'操作失败'
                            })


                        }
                        that.getList()
                    },
                    error:function (res){
                        ElMessage( {
                            type:'error',
                            message:res.msg?res.msg:'操作失败'
                        })
                        // reject(false)
                    },
                    complete:function (res){
                        if(loading){
                            loadingInstance.close();
                        }
                    }
                })
            },
            handleSelectionChange(e){
                let selectables = []
                let pk = this.options.pk?this.options.pk:'id'
                e.forEach(item=>{
                    selectables.push(item[pk])
                })
                this.selectables = selectables
            },
            handleDels(){
                let selectables = this.selectables;
                if(selectables.length==0){
                    ElMessage.warning('请选择要删除的项')
                    return
                }
                let ids = selectables.join(',')
                let url = this.options?.urls?.del?this.options.urls.del:`/app/${Config.plugin}/${Config.app}/${Config.controller}/del?ids=${ids}`
                let that = this
                ElMessageBox.confirm('确定要删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    that.handAjax(url)
                })
            },
            handleAdd(){
                let url = this.options?.urls?.add?this.options.urls.add: `/app/${Config.plugin}/${Config.app}/${Config.controller}/add`
                this.handOpen(url,"添加",["800px","90%"])
            },
            refresh(){
              this.getList()
            },
            handClick(buttons,row,area=['800px', '80%']){
                console.log(buttons,row)
                let that = this
                if(!buttons.area){
                    buttons.area =  area
                }
                if(buttons.confirm){
                    ElMessageBox.confirm(buttons.confirm,'提示',{
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(()=>{
                        that.handOneClick(buttons,row)
                    })
                }else{
                    this.handOneClick(buttons,row)
                }
            },
            handOneClick(buttons,row){
                if(!buttons.url){
                    return
                }
                let url = buttons.url
                if(row){
                    if(url.indexOf('?')==-1){
                        url += '?ids='+row.id
                    }else{
                        url += '&ids='+row.id
                    }
                }

                if(buttons.isAjax===false){
                    if(buttons.area){
                        // console.log(JSON.parse(buttons.area))
                        let area = buttons.area
                        if(typeof area == 'string'){
                            area = JSON.parse(area)
                        }
                        // let area = JSON.parse(buttons.area)
                        if(area){
                            this.handOpen(url, buttons.title||buttons.text,area)
                        }else{
                            this.handAjax(url, buttons.title||buttons.text)
                        }
                    }else{
                        this.handAjax(url, buttons.title||buttons.text)
                    }

                }else{
                    this.handAjax( url)
                }
            },
            getSeachForm(){
                let filter = {}
                let op = {}
                this.seachObj.forEach(item=>{
                    let hasvelue = item.value!=null&&item.value!=''
                    if(this.arrObj.includes(item.type)){
                        if(item.value[0]==''&&item.value[1]==''){
                            hasvelue = false
                        }
                    }
                    if(hasvelue){
                        filter[item.name] = item.value
                        if(item.operate){
                            op[item.name] = item.operate
                        }else{
                            op[item.name] = '='
                        }
                    }
                })
                return {
                    filter:JSON.stringify(filter),
                    op:JSON.stringify(op)
                }
            },
            resetSearch(){
                let seachObj = this.seachObj;
                seachObj = seachObj.map(item=>{
                    if(this.arrObj.includes(item.type)){
                        item.value = ['','']
                    }else{
                        item.value = ''
                    }
                    return item
                })
                this.seachObj = seachObj
                this.getList()
            },
            onSearch(){
                this.tableObj.page = 1;
                this.getList();
            },
            handleCurrentChange(e){
                this.tableObj.page = e;
                this.getList()
            },
            handleSizeChange(e){
                this.tableObj.limit = e
                this.getList()
            },
            handDel(row,msg='确定要删除这些数据吗?'){
                let url = (this.options.urls&&this.options.urls.del)?this.options.urls.del:`/app/${Config.plugin}/${Config.app}/${Config.controller}/del`
                if(url.indexOf('?')==-1){
                    url += '?ids='+row[this.options.pk?this.options.pk:'id']
                }else{
                    url += '&ids='+row[this.options.pk?this.options.pk:'id']
                }
                let that = this;
                ElMessageBox.confirm(
                    msg,
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(()=>{
                    this.handAjax(url,{},'get')
                })
                // this.handAjax(url,{},'get')
            },
            handAjax(url,data={},method='post'){
                let that = this
                let loading = true
                if("loading" in this.options){
                    loading = this.options.loading
                }
                let loadingInstance = null
                if(loading){
                    // console.log("loading")
                    loadingInstance = ElLoading.service({
                        fullscreen: true
                    });
                }
                $.ajax(url, {
                    method:method,
                    data:data,
                    success:function (res){
                        if(res.code==1){
                            ElMessage({
                                type:'success',
                                message:res.msg?res.msg:'操作成功',
                                duration:1000,
                                onClose:function (){
                                    that.getList()
                                }
                            })

                        }else{
                            ElMessage( {
                                type:'error',
                                message:res.msg?res.msg:'操作失败'
                            })
                        }
                    },
                    error:function (res){
                        ElMessage( {
                            type:'error',
                            message:res.msg?res.msg:'操作失败'
                        })
                    },
                    complete:function (res){
                        if(loading){
                            loadingInstance.close();
                        }
                    }
                })
                // $.get(url,function (res){
                //     loadingInstance && loadingInstance.close()
                //     if(res.code==1){
                //         ElMessage({
                //             type:'success',
                //             message:res.msg?res.msg:'操作成功',
                //             duration:1000,
                //             onClose:function (){
                //                 that.getList()
                //             }
                //         })
                //
                //     }else{
                //         ElMessage( {
                //             type:'error',
                //             message:res.msg?res.msg:'操作失败'
                //         })
                //     }
                // })
            },
            handOpen(url,title,area=['80%', '80%']){
                // console.log(url,'urlurlurlurlurlurlurlurl')
                // if(!url){
                //     return
                // }
                console.log(area,'area')
                let that = this
                layer.open({
                    type:2,
                    title: title,
                    content: url,
                    area: area,
                    callback:function (layero, index) {
                        console.log("callback")

                    },
                    end:function (){
                        // console.log('end')
                        that.getList()
                    },
                    success:function (layero, index){
                        console.log('success')
                    }

                })
            },
            handEdit(row,area=['800px', '90%']){
                // console.log(row)
                var editUrl = (this.options.urls&&this.options.urls.edit)?this.options.urls.edit:`/app/${Config.plugin}/${Config.app}/${Config.controller}/edit`
                if(editUrl.indexOf('?')==-1){
                    editUrl = editUrl+'?ids='+row[this.options.pk?this.options.pk:'id']
                }else{
                    editUrl = editUrl+'&ids='+row[this.options.pk?this.options.pk:'id']
                }
                this.handOpen(editUrl,"编辑", area)
            },
            getDate(value){
                value = value + ``
                let res = this.isTimestampAndValidDate((JSON.parse(JSON.stringify(value))));
                if(res){

                    if(value.length==10){
                        value = parseInt(value)*1000
                    }else{
                        value = parseInt(value)
                    }
                    return this.formatDate(new Date(value),'yyyy-MM-dd hh:mm:ss')
                }
                return value
            },
            formatDate(date, fmt){
                var o = {
                    "MM": date.getMonth() + 1, //月份
                    "dd": date.getDate(), //日
                    "hh": date.getHours(), //小时
                    "mm": date.getMinutes(), //分
                    "ss": date.getSeconds(), //秒
                    "qq": Math.floor((date.getMonth() + 3) / 3), //季度
                    "S": date.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    }
                }
                return fmt;
            },
            isTimestampAndValidDate(str){
                if (!/^\d+$/.test(str)) {
                    return false;
                }
                const timestamp = parseInt(str, 10);
                const date = new Date(timestamp * 1000); // 假设是秒数，需要乘以1000转为毫秒
                return !isNaN(date.getTime());
            },
            getList(){
                let searchForm = this.getSeachForm()
                console.log(searchForm,'ssssssssssssssss')
                let data = {
                    page:this.tableObj.page,
                    limit:this.tableObj.limit,
                    ...searchForm
                }
                if(this.options.isTree){
                    data.list_type = 'tree'
                    delete data.page
                    delete data.limit
                }
                if(this.options.pk){
                    data.pk = this.options.pk
                }
                if(this.options.sort){
                    data.sort = this.options.sort
                }
                if(this.options.order){
                    data.order = this.options.order
                }
                let newurl = ''
                if(!(this.options&&this.options.url&&this.options.url.index)){
                   newurl = `/app/${Config.plugin}/${Config.app}/${Config.controller}/index`
                }else{
                   newurl = `/app/${Config.plugin}/${Config.app}/${Config.controller}/${this.options.url.index}`
                }
                let loading = true
                if("loading" in this.options){
                    loading = this.options.loading
                }
                let loadingInstance = null
                if(loading){
                    // console.log("loading")
                    loadingInstance = ElLoading.service({
                        fullscreen: true
                    });
                }
                let that = this
                $.post(newurl,data,function (res){
                    if(loading){
                        // console.log("进入回调")
                        loadingInstance.close()
                    }
                    // console.log(res,'rrrrrrrrrr')
                    if(res.code==1){
                        that.tableObj.total = res.data.total
                        that.tableObj.rows = res.data.rows
                        // console.log(that.tableObj.rows,'999999')
                    }
                })
            }
        }
    }
    return mutable
})